import store from '../store';

const wsURL = import.meta.env.VITE_WS_PATH;

const webSocket = {
  websocket: null,
  // 初始化weosocket
  wsInit(): void {
    if (typeof WebSocket === 'undefined') {
      console.error('您的浏览器不支持WebSocket');
      return;
    }

    this.websocket = new WebSocket(wsURL);
    this.websocket.onopen = (event) => {
      // 握手
      const data = {option: 'login', data: {token: localStorage.getItem('token')}};
      if (this.websocket.readyState === 1) {
        this.wsSend(data);
      }
    };
    this.websocket.onerror = this.wsOnerror;
    this.websocket.onmessage = this.wsOnMessage;
    this.websocket.onclose = this.wsClose;

    store.commit('setWebsocketInt', this.websocket);
  },
  wsOnerror(e) {
    // console.log("WebSocket连接发生错误", e);
  },
  // 关闭
  wsClose(e) {
    // console.log("connection closed");
    webSocket.wsInit();
    // console.log('restart')
  },
  // 数据接收
  wsOnMessage(e: any) {
    const jsonData = eval('(' + e.data + ')');
    store.commit('setMessageData', jsonData);
  },
  // 数据发送
  wsSend(agentData: {option: string; data: {token: string | null}}) {
    webSocket.websocket.send(JSON.stringify(agentData));
  },
  // 心跳
  wsHeartbeat() {
    const heartbeatData = {
      option: '',
      data: {
        token: localStorage.getItem('token'),
      },
    };
    if (this.websocket.readyState === 1) {
      webSocket.websocket.send(JSON.stringify(heartbeatData));
    }
  },
};

export default webSocket;
